﻿using Microsoft.Win32;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Management;

namespace TYBase
{
    public static class SystemHelper
    {
        private static string _ProcessName;
        public static string ProcessName()
        {
            if (_ProcessName.Null())
            {
                _ProcessName = Process.GetCurrentProcess().ProcessName;
            }
            return _ProcessName;
        }
        public static bool SingleApp()
        {
            Process[] pros = Process.GetProcesses();
            int n = pros.Where(p => p.ProcessName.Equals(ProcessName())).Count();
            if (n > 1)
            {
                return false;
            }
            return true;
        }
        public static Dictionary<int, string> GetComInfo()
        {
            Dictionary<int, string> dicData = new Dictionary<int, string>();
            var portnames = SerialPort.GetPortNames();
            using (var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE Caption like '%(COM%'"))
            {
                var ports = searcher.Get().Cast<ManagementBaseObject>().ToList().Select(p => p["Caption"].ToString());

                foreach (var item in portnames)
                {
                    var port = ports.FirstOrDefault(x => x.Contains(item));

                    if (int.TryParse(item.Replace("COM", ""), out int val))
                    {
                        dicData.Add(val, port == null ? "" : port);
                    }
                }
            }
            return dicData.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
        }

        /// <summary>
        /// 浏览文件
        /// </summary>
        /// <param name="filePath"></param>
        public static void ExploreFile(string filePath)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "explorer";
            //打开资源管理器
            proc.StartInfo.Arguments = @"/select," + filePath;
            //选中"notepad.exe"这个程序,即记事本
            proc.Start();
        }

        /// <summary>
        /// 浏览文件夹
        /// </summary>
        /// <param name="path"></param>
        public static void ExplorePath(string path)
        {
            System.Diagnostics.Process.Start("explorer.exe", path);
        }

        /// <summary>
        /// checking whether the specified COM component is registered in the system
        /// </summary>
        /// <param name = "clsid"> COM component designated Class Id </ param>
        /// <returns> true: indicates registration; false: unregistered represents </ returns>
        public static bool IsRegistered(string clsid)
        {
            try
            {
                // parameter checking
                System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(clsid), "clsid should not be empty");

                //计算机\HKEY_CLASSES_ROOT\WOW6432Node\CLSID\{28E68F9A-8D75-11D1-8DC3-3C302A000000}
                // Check method to find whether there is a specified registry clsid
                string key = string.Format(@"CLSID\{{{0}}}", clsid);
                RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(key);
                if (regKey != null)
                {
                    return true;
                }
                key = string.Format(@"WOW6432Node\CLSID\{{{0}}}", clsid);
                regKey = Registry.ClassesRoot.OpenSubKey(key);
                if (regKey != null)
                {
                    return true;
                }
                return false;
            }
            catch (System.Exception)
            {

                return false;
            }

        }//end method

        public static bool RegisterOCX(string path)
        {
            try
            {
                Process p = new Process();
                p.StartInfo.FileName = $"Regsvr32.exe";
                p.StartInfo.Arguments = $"/s  {path}"; // no space in the path
                p.Start();
                p.WaitForExit();
                return true;
            }
            catch (System.Exception)
            {

                return false;
            }

        }//end method

        //28E68F91-8D75-11D1-8DC3-3C302A000000
    }
}